/**
 * 
 */
package com.ditty.kit;

import java.util.List;

import com.ditty.common.LinkedObject;

/**
 * @author dingnate
 *
 */
public class LinkedKit {
	LinkedKit() {
	}

	/**
	 * 构造链表
	 * 
	 * @param linkedObjects
	 * @param tail
	 * @return
	 */
	public static <T extends LinkedObject<T>> T buildLinkedObjects(List<T> linkedObjects, T tail) {
		T currentObj = tail;
		for (int i = linkedObjects.size() - 1; i >= 0; i--) {
			T tmp = linkedObjects.get(i);
			if (tmp == null) {
				continue;
			}
			getTail(tmp).next = currentObj;
			currentObj = tmp;
		}
		return currentObj;
	}

	public static <T extends LinkedObject<T>> T buildLinkedObjects(T... linkedObjects) {
		T currentObj = null;
		for (int i = linkedObjects.length - 1; i >= 0; i--) {
			T tmp = linkedObjects[i];
			if (tmp == null) {
				continue;
			}
			getTail(tmp).next = currentObj;
			currentObj = tmp;
		}
		return currentObj;
	}

	/**
	 * 反转链表
	 * 
	 * @param head
	 * @return
	 */
	public static <T extends LinkedObject<T>> T reverse(T head) {
		T before = head;
		T after = before.next;
		while (after != null) {
			T tmp = after.next;
			after.next = before;
			before = after;
			after = tmp;
		}
		return before;
	}

	/**
	 * 获取链表最后一个元素
	 * 
	 * @param head
	 * @return
	 */
	public static <T extends LinkedObject<T>> T getTail(T head) {
		T tail = head;
		while (tail.next != null) {
			tail = tail.next;
		}
		return tail;
	}
}
